<?php
/**
 * 候选人才
 */

namespace app\v1_0\controller\member;

use app\common\model\Category;
use app\common\model\CompanyStaffManage;
use app\common\model\Resume;
use app\common\model\ResumeContact;
use app\common\model\ResumeEducation;
use app\common\model\ResumeIntention;
use app\common\model\Uploadfile;
use Think\Db;
use think\Exception;

class ResumeCandidate extends \app\v1_0\controller\common\Base
{
    public $status_list = [1=>'待筛选',3=>'待%s面试',5=>'一轮面试通过',6=>'二轮面试通过',7=>'三轮面试通过',8=>'四轮面试通过',9=>'通过',12=>'已入职'];
    public $interview_arr = [1=>'一',2=>'二',3=>'三',4=>'四'];
    public function _initialize()
    {
        parent::_initialize();
        $this->checkLogin(3);
        $staff = CompanyStaffManage::where('uid', $this->userinfo->uid)->field('id,com_id,coms_d_id')->find();

        $staff = $staff?$staff->toArray():[];
        $this->userinfo = array_merge((array)$this->userinfo,$staff);
    }

    public function index()
    {
        $offset = input('pagesize', 10);
        $status = input('status', 1);
        $status_list = [1, 3, 9, 12];
        if (!in_array($status, $status_list)) {
            return $this->returnJson(500, '状态值传参有误');
        }
        $department = $this->userinfo;

        $res = \app\common\model\ResumeCandidate::
            where('recruit_uid',$department['id'])
            ->where('company_id',$this->userinfo['com_id'])
//            ->when($status==3,function ($q){
//                $q->whereIn('status', [3,5,6,7,8]);
//            },function ($q)use($status){
//                $q->where('status', $status);
//            })
            ->where('status', $status)
            ->field('id,resume_id,command_id,status,interview_time')
            ->order('id', 'desc')
            ->paginate($offset)->toArray();
        $work_list = model('ResumeWork')
            ->where('rid', 'in', array_column($res['data'], 'resume_id'))
            ->field('rid,jobname')
            ->order('id desc')
            ->select();
        $work_data = [];
        foreach ($work_list as $v) {
            if (isset($work_data[$v['rid']])) continue;
            $work_data[$v['rid']] = $v['jobname'];
        }
//        $res = $res;
        $request['result'] = $res['data'];
        $request['join'] = [
            'resume' => ['model' => Resume::class,
                'field' => 'id,fullname,sex,birthday,enter_job_time,download_time,refreshtime,photo_img,education',
                'key' => 'id',
                'foreign_key' => 'resume_id'],
            'intention' => ['model' => ResumeIntention::class,
                'field' => 'rid,category_text,district_text',
                'key' => 'rid',
                'foreign_key' => 'resume_id']
        ];
        $res['data'] = leftJoinData($request);
        $year = date('Y');
        $photo_data = $photo_data = model('Uploadfile')->getFileUrlBatch(
            array_column($res['data'], 'photo_img')
        );
//        $btns = $this->btnList($status);
        foreach ($res['data'] as &$v) {
            $v['addtime'] = $v['download_time']?:$v['refreshtime'];
            $v['interview_time'] && $v['interview_time'] = date('Y-m-d H:i',$v['interview_time']);
            $v['age'] = $year - intval($v['birthday']);
            $v['sex_text'] = model('Resume')->map_sex[$v['sex']] ?? '';
            $v['experience_text'] = $v['enter_job_time'] == 0 ? '无经验' : format_date($v['enter_job_time']) . '经验';
            $v['education_text'] = model('BaseModel')->map_education[$v['education']] ?? '';
            $v['recent_work'] = $work_data[$v['resume_id']] ?? '';
            $v['photo_img_src'] = $photo_data[$v['photo_img']] ?? default_empty('photo', $v['sex']);
            $v['status_name'] = $v['status']==3?
                sprintf($this->status_list[$v['status']]??'%s',$v['command_id']?($this->interview_arr[$v['command_id']].'轮'):''):
                $this->status_list[$v['status']]??'';
            $v['btns'] = $this->btnList($v['status'],$v);
            unset($v['birthday'], $v['enter_job_time'], $v['rid'], $v['education'], $v['sex']);
        }

        // 统计各个状态的数量
        $statistics = \app\common\model\ResumeCandidate::
            where('company_id',$this->userinfo['com_id'])
            ->where('recruit_uid',$department['id'])
            ->whereIn('status', $status_list)
            ->field('count(*) as count,status')->group('status')->select();

        $res['statistics'] = array_column_G($statistics, 'count', 'status');
//        foreach ($res['statistics'] as $key=>$val){
//            if(!in_array($key,$status_list)){
//                $res['statistics'][3] = $res['statistics'][3]??0;
//                $res['statistics'][3] += $val;
//                unset($res['statistics'][$key]);
//            }
//        }

        return $this->returnJson(200, 'success', $res);
    }

    public function detail()
    {

        $id = input('id/d', 0);
        $res = \app\common\model\ResumeCandidate::where('id', $id)
            ->with(['education' => function ($q) {
                $q->field('rid,school,major,starttime,endtime,todate,education');
            }, 'intention' => function ($q) {
                $q->field('rid,category_text,minwage,maxwage,district_text,nature,trade');
            }, 'work' => function ($q) {
                $q->field('rid,companyname,jobname,starttime,endtime,todate,duty');
            }, 'training' => function ($q) {
                $q->field('rid,agency,course,starttime,endtime,todate,description');
            }, 'project' => function ($q) {
                $q->field('rid,projectname,role,starttime,endtime,todate,description');
            }, 'certificate' => function ($q) {
                $q->field('rid,name,obtaintime');
            }, 'language' => function ($q) {
                $q->field('rid,language,level');
            }, 'enclosure' => function ($q) {
                $q->field('rid,enclosure,title');
            }])
            ->field('id,resume_id,command_id,status')
            ->find();
        if (!$res) {
            return $this->returnJson(500, '信息有误');
        }
        $request['result'] = $res->toArray();
        $request['join'] = [
            'resume' => ['model' => Resume::class,
                'field' => 'id,fullname,sex,birthday,enter_job_time,download_time,refreshtime,photo_img,specialty,tag,education as r_education',
                'key' => 'id',
                'foreign_key' => 'resume_id'],
            'contact' => ['model' => ResumeContact::class,
                'field' => 'rid,mobile,email,weixin',
                'key' => 'rid',
                'foreign_key' => 'resume_id'],
        ];
        $res = leftJoinData($request, 1);
        // 基本信息
        $year = date('Y');
        $photo_data = $photo_data = model('Uploadfile')->getFileUrlBatch(
            [$res['photo_img']]
        );
        $res['addtime'] = $res['download_time']?:$res['refreshtime'];
        $res['age'] = $year - intval($res['birthday']);
        $res['sex_text'] = model('Resume')->map_sex[$res['sex']] ?? '';
        $res['experience_text'] = $res['enter_job_time'] == 0 ? '无经验' : format_date($res['enter_job_time']) . '经验';
        $res['education_text'] = model('BaseModel')->map_education[$res['r_education']] ?? '';
        $res['recent_work'] = $work_data[$res['resume_id']] ?? '';
        $res['photo_img_src'] = $photo_data[$res['photo_img']] ?? default_empty('photo', $res['sex']);
        $res['status_name'] = $v['status_name'] = $res['status']==3?
            sprintf($this->status_list[$res['status']]??'%s',$res['command_id']?($this->interview_arr[$res['command_id']].'轮'):''):
            $this->status_list[$res['status']]??'';
        $res['btns'] = $this->btnList($res['status'],$res);
        unset($res['birthday'], $res['enter_job_time'], $res['rid'], $res['r_education'], $res['sex']);

        $new_resume = new Resume();
        // 工作意向
        if ($res['intention']) {
            $intention = $res['intention'];
            $intention['wage_text'] = sprintf('%sk-%sk', round($intention['minwage'] / 1000,1), round($intention['maxwage'] / 1000,1));
            $intention['nature_text'] = $new_resume->map_nature[$intention['nature']] ?? '';
            $intention['trade_text'] = $intention['trade'] ? Category::where('id', $intention['trade'])->value('name') : '';
            unset($intention['trade'], $intention['nature'], $intention['minwage'], $intention['maxwage']);
            $res['intention'] = $intention;
        }

        // 标签
        $res['selectedTags'] = [];
        if ($res['tag']) {
            $category_data = model('Category')->getCache();
            $selectedTags = [];
            $tag_arr = explode(',', $res['tag']);
            foreach ($tag_arr as $k => $v) {
                if (
                    is_numeric($v) &&
                    isset($category_data['QS_resumetag'][$v])
                ) {
                    $selectedTags[]['text'] = $category_data['QS_resumetag'][$v];
                } else {
                    $selectedTags[]['text'] = $v;
                }
            }
            $res['selectedTags'] = $selectedTags;
        }
        unset($res['tag']);
        // 教育
        $res['educationList'] = $res['education'];
        if ($res['education']) {
            $values = $res['education'];
            foreach ($values as $key => $value) {
                $value['starttime'] = date('Y-m-d', $value['starttime']);
                $value['endtime'] = $value['todate'] ? '至今' : date('Y-m-d', $value['endtime']);
                $values[$key] = $value;
            }
            $res['educationList'] = $values;
        }
        unset($res['education']);
        // 工作经历
        $res['workList'] = $res['work'];
        if ($res['work']) {
            $values = $res['work'];
            foreach ($values as $key => $value) {
                $value['starttime'] = date('Y-m-d', $value['starttime']);
                $value['endtime'] = $value['todate'] ? '至今' : date('Y-m-d', $value['endtime']);
//                $value['duty'] = preg_replace('/\\n/','<br/>',$value['duty']);
                $values[$key] = $value;
            }
            $res['workList'] = $values;
        }
        unset($res['work']);

        // 培训经历
        $res['trainList'] = $res['training'];
        if ($res['training']) {
            $values = $res['training'];
            foreach ($values as $key => $value) {
                $value['starttime'] = date('Y-m-d', $value['starttime']);
                $value['endtime'] = $value['todate'] ? '至今' : date('Y-m-d', $value['endtime']);
                $values[$key] = $value;
            }
            $res['trainList'] = $values;
        }
        unset($res['training']);

        // 项目经验
        $res['projectList'] = $res['project'];
        if ($res['project']) {
            $values = $res['project'];
            foreach ($values as $key => $value) {
                $value['starttime'] = date('Y-m-d', $value['starttime']);
                $value['endtime'] = date('Y-m-d', $value['endtime']);
                $values[$key] = $value;
            }
            $res['projectList'] = $values;
        }
        unset($res['project']);

        // 证书
        $res['certificateList'] = $res['certificate'];
        if ($res['certificate']) {
            $values = $res['certificate'];
            foreach ($values as $key => $value) {
                $value['obtaintime'] = date('Y-m-d', $value['obtaintime']);
                $values[$key] = $value;
            }
            $res['certificateList'] = $values;
        }
        unset($res['certificate']);

        // 语言
        $category_data = model('Category')->getCache();
        $language_library = $category_data['QS_language'];
        $language_level_library = $category_data['QS_language_level'];
        $res['languageList'] = $res['language'];
        if ($res['language']) {
            $values = $res['language'];
            foreach ($values as $key => $value) {
                $value['language'] = $language_library[$value['language']]??'';
                $value['level'] = $language_level_library[$value['level']]??0;
                $values[$key] = $value;
            }
            $res['languageList'] = $values;
        }
        unset($res['language']);

        // 附件
        $res['enclosure_resume'] = $res['enclosure'];
        unset($res['enclosure']);

        return $this->returnJson(200, 'success', $res);


    }

    private function btnList($status,$v)
    {
        $interview_arr = $this->interview_arr;
        $btns = [
            'weed_out' => [
                'name' => '淘汰',
                'callback' => 'weed_out',
                'style' => 'background:#ff5d3c;color:#fff'
            ],
            'interview' => [
                'name' => '安排面试',
                'callback' => 'interview',
                'style' => 'background:#1787fb;color:#fff'
            ],
            'pass' => [
                'name' => ($interview_arr[$v['command_id']]??'一').'轮通过',
                'callback' => 'pass',
                'style' => 'background:#1787fb;color:#fff'
            ],
//            'complete' => [
//                'name' => '面试完成',
//                'callback' => 'complete',
//                'style' => 'background:#1787fb;color:#fff'
//            ]
        ];
        switch ($status) {
            case 1:
                return [
                    $btns['weed_out'],
                    $btns['interview']
                ];
                break;
            case 3:
                return [
                    $btns['weed_out'],
                    $btns['pass']
                ];
                break;
            case 5:
            case 6:
            case 7:
            return [
                $btns['weed_out'],
//                $btns['interview'],
//                $btns['complete']
            ];
            case 8:
                return [
                    $btns['weed_out'],
                    $btns['complete']
                ];
            break;
            case 9:
                return [];
                break;
            case 12:
                return [];
                break;
            default:
                return [];
        }
    }

    public function updateStatus()
    {
        $content = input('post.content/a');
        $id = input('id/d', 0);
        if(!$remark = input('recruit_remark','')){
            return $this->returnJson(500,'请输入备注');
        }
        if (!$res = \app\common\model\ResumeCandidate::where('id', $id)->field('id,command_id')->find()) {
            return $this->returnJson(500, 'id参数有误');
        }
        $data = [
            'status' => input('post.status/d', 0, 'intval'),
            'recruit_uid' => $this->userinfo['id'],
            'interview_time' => !empty($content['mtime'])?strtotime($content['mtime']):0,
            'recruit_remark' => $remark,
        ];
        !empty($content['command_id']) && $data['command_id'] = $content['command_id'];
        if($data['status'] == 5){
            $command_id_to_status = [1=>5,2=>6,3=>7,4=>8];
            $data['status'] = $command_id_to_status[$res['command_id']]??5;
        }
        $result = model('ResumeCandidate')
            ->validate(true)
            ->allowField(true)
            ->save($data, ['id' => $id]);
        if (false === $result) {
            return $this->returnJson(500, model('ResumeCandidate')->getError());
        }
        return $this->returnJson(200, '操作成功');
    }

    public function weedOut()
    {
        $id = input('id/d', 0);
        if (\app\common\model\ResumeCandidate::where('id', $id)->count() <= 0) {
            return $this->returnJson(500, 'id参数有误');
        }
        $result = model('ResumeCandidate')
            ->validate(true)
            ->where('id', $id)
            ->delete();
        if (false === $result) {
            return $this->returnJson(500, model('ResumeCandidate')->getError());
        }
        return $this->returnJson(200, '操作成功');
    }
}
